package com.matt.docpro.controller;

import com.matt.docpro.config.Utils;
import com.matt.docpro.model.Blog;
import com.matt.docpro.model.User;
import com.matt.docpro.service.BlogService;
import com.matt.docpro.service.LoginInfoService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.List;

/**
 * BlogController
 * Created by  on 2024/02/28.
 */
@Controller
public class BlogController {
    @Autowired
    BlogService blogService;
    @Autowired
    LoginInfoService loginInfoService;

    @RequestMapping("/blog")
    public String init(Model model, HttpServletRequest request) {
        String token = Utils.getToken(request);
        User user = loginInfoService.getUserByToken(token);
        List<Blog> blogs = blogService.getAll();
        model.addAttribute("blogs", blogs);
        model.addAttribute("user", user);
        return "blog";
    }

    @RequestMapping("/blog-details")
    public String blogDetails(Model model, String id, HttpServletRequest request) {
        String token = Utils.getToken(request);
        User user = loginInfoService.getUserByToken(token);
        Blog blog = blogService.getById(id);
        List<Blog> recentBlogs = blogService.getAll();
        if (recentBlogs.size() > 3) {
            recentBlogs = recentBlogs.subList(0,3);
        }
        model.addAttribute("blog", blog);
        model.addAttribute("recentBlogs", recentBlogs);
        model.addAttribute("user", user);
        return "blog-details";
    }
}
